from library.expand.log import logger
from library.expand import Const
from library.event.IEvent import eventArgs

class EventModel(object):
    __eNamespace__=""
    __eClass__=""
    __eMethod__=""
    def __init__(self,_namespace,_class,_method):
        self.__eNamespace__=_namespace
        self.__eClass__=_class
        self.__eMethod__=_method

class sysEventManager:
    eventList=dict({})
    def __init__(self):
        pass

    def addEventListen(self,key,bound,eModel):
        try:
            if key not in self.eventList:
                self.eventList[key]=({bound:eModel})
                return True
            else:
                if bound not in self.eventList[key]:
                    self.eventList[key][bound]=eModel
                    return True
                else:
                    return False
        except Exception as e:
            return False

    def removeEventListen(self,key,bound=None):
        try:
            if key in self.eventList:
                if not bound:
                    if bound in self.eventList[key]:
                        del self.eventList[key][bound]
                        return True
                else:
                   del self.eventList[key]
                   return True
            return True
        except:
            return False

    def call(self,key,bound,*args,**kw):
        try:
            if key in self.eventList:
                if bound in self.eventList[key]:
                    handle=__import__(self.eventList[key][bound].__eNamespace__,fromlist=(True))
                    if handle:
                        if hasattr(handle,self.eventList[key][bound].__eClass__):
                            func=getattr(handle,self.eventList[key][bound].__eClass__)
                            if func:
                                if self.eventList[key][bound].__eMethod__:
                                    runTime=func(*args)
                                    method=getattr(runTime,self.eventList[key][bound].__eMethod__)
                                    if method:
                                        #customer's event function
                                        return method(*args,**kw)
                                else:
                                    #default event main function
                                    return func(*args).todo(*args,**kw)
            return None
        except Exception as e:
            logger.error(e)
            return None

Const.SYSEVENT=sysEventManager()